<?php

namespace app\data\controller\channel;

use app\data\model\DataUserAccount;
use app\data\model\DataUserTransfer;
use app\data\model\DataWechat;
use app\data\model\ShopOrder;
use think\admin\Controller;
use think\admin\helper\QueryHelper;

/**
 * 公众号管理
 * Class Mark
 * @package app\data\controller\wechat
 */
class Wechat extends Controller
{
    /**
     * 公众号管理
     * @auth true
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        DataWechat::mQuery()->layTable(function () {
            $this->title = '公众号管理';
        }, function (QueryHelper $query) {
            $query->where(['channel' => 1]);
            $query->like('name')->dateBetween('created_at');
        });
    }

    /**
     * 添加公众号
     * @auth true
     */
    public function add()
    {
        DataWechat::mForm('form');
    }

    /**
     * 编辑公众号
     * @auth true
     */
    public function edit()
    {
        DataWechat::mForm('form');
    }
    /**
     * 订单列表处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _index_page_filter(array &$data)
    {
        foreach ($data as &$v){
            $v['not_settlement_amount'] = 0;
            $amount = ShopOrder::info(array(
                'channel_code'  => $v['code'],
                'has_settle_account'=>0
            ),"sum(payment_amount) as payment_amount");
            $v['not_settlement_amount'] = $amount['payment_amount']/100??0;
            $v['settlement_amount'] = $v['settlement_amount']/100??0;
            $v['withdraw_amount'] = $v['withdraw_amount']/100??0;
        }
    }
    /**
     * 表单数据处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _form_filter(array &$data)
    {
        if ($this->request->isPost()) {
            //校验是否存在
            $info = DataWechat::info(array(
                'appid' => $data['appid'],
                'channel'=>1
            ),'id');
            if(empty($info) === FALSE){
                if(isset($data['id'])  && empty($data['id']) === FALSE){
                    if($info['id'] != $data['id']){
                        $this->error("信息有误，请确认！");
                    }
                }
            }
            //生成带参数二维码
            if(!isset($data['id'])  || empty($data['id'])){
                $data['created_at'] = \Tools::getDateTimeByTime();
                $salt = rand(1000,9999);
                $data['code'] = \Tools::SHA256($data['appid'].$salt);
                $data['check_pwd'] = $data['code'];
                $data['salt'] = $salt;
                //生成带参数二维码
                $data['qrcode_path'] = \Common::createQrcode(array(
                    'channel_code'      => $data['code'],
                    'channel'           =>1
                ),1);
            }else{
                unset($data['appid']);
            }
            $data['updated_at'] = \Tools::getDateTimeByTime();
        }
    }
    /**
     * 表单结果处理
     * @param bool $state
     * @return void
     */
    protected function _form_result(bool $state)
    {
        if ($state) {
            $this->success('成功', "javascript:$('#TagsData').trigger('reload')");
        }
    }

    /**
     * 删除公众号
     * @auth true
     */
    public function remove()
    {
        DataWechat::mDelete();
    }

    /**
     * 下载二维码
     * @return void
     */
    public function download(){
        $id = input('id','','trim,intval');
        if(empty($id)) $this->error('信息有误');
        $info = DataWechat::info(array(
            'id'=>$id
        ),'qrcode_path');
        if(empty($info) || empty($info['qrcode_path'])) $this->error('信息有误');
        \Common::downloadQrcode($info);
    }
    public function down(){

    }
    /**
     * 结算
     * @return void
     */
    public function settlement(){
        $id = input('id',0,'trim,intval');
        if(empty($id)) $this->error('信息有误');
        $info = DataWechat::info(array(
            'id'=>$id
        ));
        if(empty($info) || empty($info['code'])) $this->error('信息有误');
         //获取可结算额度  一周以前的  七号后可放开
        $can_jiesuantime = sysconf('channel_can_jiesuantime');
        $date = date('d');
        if($date < $can_jiesuantime)  $this->error('未到结算日期');
        $start_time = \Tools::getDateTimeByTime(strtotime("-1 months"),'Y-m').'-01 00:00:01';
        $end_time = \Tools::getDateTimeByTime(time(),'Y-m').'-01 00:00:01';
        $payment_amount = ShopOrder::info(array(
            ['channel_code','=',$info['code']],
            ['has_settle_account' ,'=',0],
            ['status','=',6],
            ['finish_datetime','between',[$start_time,$end_time]]
        ),"sum(payment_amount) as payment_amount");
        $amount = 0;
        $amount = self::getTicheng($payment_amount['payment_amount']??0);
        if($this->request->isPost()){
            //提交结算
            $up_amount = input('amount',0,'trim');
            if($up_amount <= 0)  $this->error('可结算金额不正确，请确认后再试');
            if($up_amount > $amount)  $this->error('可结算金额不正确，请确认后再试');
            $opera = [];
            $userDataWechatModel = new \app\data\model\DataWechat();
            $userDataWechatModel->startTrans();
            //记录提交记录
            $opera[] = DataUserTransfer::createData(array(
                'date'  => \Tools::getDateTimeByTime(time(),'Y-m-d'),
                'code'  =>\Common::uniqidDate(16,'W'),
                'amount'    =>$amount*100,
                'bank_name'=>$info['bank_name'],
                'bank_bran'=>$info['bank_child_name'],
                'bank_user'=>$info['invoice_name'],
                'bank_code'=>$info['bank_code'],
                'remark'=>input('audit_remark'),
                'audit_remark'=>input('audit_remark'),
                'audit_datetime'=>\Tools::getDateTimeByTime(),
                'create_at'=>\Tools::getDateTimeByTime(),
                'change_time'=>\Tools::getDateTimeByTime(),
                'audit_status'=>1,
                'channel'=>$info['channel'],
                'channel_code'=>$info['code'],
            ));
            //标记未打款  增加结算金额
            if($amount > 0) $opera[] = DataWechat::update(array(
                'settlement_amount' => $info['settlement_amount'] + $amount * 100,
                'updated_at'        =>\Tools::getDateTimeByTime()
            ),array(
                'id'    => $info['id']
            ))->save();
            //标记订单为已结算
            $opera[] = ShopOrder::update(array(
                'has_settle_account'    => 1
            ),array(
                ['channel_code','=',$info['code']],
                ['has_settle_account' ,'=',0],
                ['status','=',6],
                ['finish_datetime','between',[$start_time,$end_time]]
            ))->save();
            //提交事务
            if(\Tools::checkArrayResult($opera)) {
                $userDataWechatModel->commit();
                $this->success('结算成功');
            }else{
                $userDataWechatModel->rollback();

                sysoplog('结算',json_encode($opera));
                $this->error('结算失败，请重试');
            }
        }
        $this->amount = $amount;
        $this->id = $id;
        $this->fetch();
    }

    /**
     * 财务明细
     * @return void
     */
    public function settlementNote(){
        $id = input('id',0,'trim,intval');
        $channel_code = '';
        if(empty($id)=== FALSE) {
            $info = DataWechat::info(array(
                'id' => $id
            ));
            if (empty($info) === FALSE) $channel_code = $info['code'];
        }
        $this->title = '渠道财务明细';
        // 状态数据统计
        $query = DataUserTransfer::mQuery();
        $query->dateBetween('create_at')->whereIn('audit_status','1,2')->whereIn('channel','1,2');
        if(empty($channel_code) === FALSE){
            $query->where('channel_code',$channel_code);
        }else {
            if (empty(input('name')) === FALSE) {
                // 渠道搜索查询
                $db = DataWechat::mQuery()->like('name#name')->db();
                if ($db->getOptions('where')) $query->whereRaw("channel_code in {$db->field('code')->buildSql()}");
            }
        }
        // 分页排序处理
        $query= $query->order('id desc')->field('*');
        if(input('output') == 'json'){
            $query->page();
        }else{
            $lists = $query->page(true, false, false);
        }
        if (empty($lists['list']) === FALSE) {
            foreach ($lists['list'] as &$lv) {
                $lv['amount'] = sprintf("%.2f",$lv['amount']/100);
                $dataWechatInfo = DataWechat::info(array('code'=>$lv['channel_code']));
                $lv['name'] = $dataWechatInfo['name'];
            }
        }
        $this->list = $lists['list'];
        $this->fetch();
    }
    /**
     * 上传打款凭证
     * @return void
     */
    public function markPay(){
        $id = input('id',0,'trim,intval');
        if(empty($id)) $this->error('信息有误');
        $info = DataWechat::info(array(
            'id'=>$id
        ));
        if(empty($info) || empty($info['code'])) $this->error('信息有误');
        if($this->request->isPost()){
            $opera = [];
            $userDataWechatModel = new \app\data\model\DataWechat();
            $userDataWechatModel->startTrans();
            $amount = input('amount','','trim');
            //扣减已结算
            if($amount > 0) $opera[] = DataWechat::update(array(
                'settlement_amount' => $info['settlement_amount'] - $amount * 100,
                'updated_at'        =>\Tools::getDateTimeByTime()
            ),array(
                'id'    => $info['id']
            ))->save();
            //增加已打款
            if($amount > 0) $opera[] = DataWechat::update(array(
                'withdraw_amount' => $info['withdraw_amount'] + $amount * 100,
                'updated_at'        =>\Tools::getDateTimeByTime()
            ),array(
                'id'    => $info['id']
            ))->save();
            //标记结算记录为已打款
            $opera[] = DataUserTransfer::update(array(
                'audit_status'  => 2,
                'change_time'   => \Tools::getDateTimeByTime(),
                'audit_remark'  => '管理员：'.$this->app->session->get('user.username').'标记打款成功，金额：'.$amount
            ),array(
                'audit_status'  =>1,
                'channel_code'  =>$info['code'],
                'channel'       =>$info['channel']
            ))->save();
            if(\Tools::checkArrayResult($opera)){
                $userDataWechatModel->commit();
                $this->success('标记成功');
            }else{
                $userDataWechatModel->rollback();
                sysoplog('标记打款失败',json_encode($opera));
                $this->error('标记失败，请重试');
            }
        }
        $this->amount = $info['settlement_amount']/100 ?? 0;
        $this->id = $id;
        $this->fetch();
    }


}
